<?php
define('ROOT_PATH', dirname(dirname(dirname(dirname(__FILE__)))) . '/');
$basename = basename($_SERVER['SCRIPT_FILENAME']);
$basename = explode('.',$basename );
define('CURSCRIPT', reset($basename));
include ROOT_PATH.'inc/class/application.class.php';
application::init();

$post = $_POST;
$uid = $post['uid'];
$member = DB::fetch_first("SELECT `uid`, `login_id` FROM " . DB::table('member') . " WHERE `uid`='" . $uid . "' AND `login_name`='xiaochengxu'");
if (empty($member)) { echo json_encode(array('r' => -1, 'errmsg' => '用户(ID: '.$uid.')不存在')); exit; }
$money = $post['fee']; // 支付金额,单位分
if (empty($money) || intval($money) < 0) { echo json_encode(array('r' => -1, 'errmsg' => '支付金额必须大于0')); exit; }

$stype = 'one_year'; // 一年的VIP会员
if (isset($post['stype']) && !empty($post['stype'])) {
    $stype = $post['stype'];
}
$fee = DB::result_first("SELECT `fee` FROM " . DB::table('pdd_vip_setting') . " WHERE `stype` = '" . $stype . "'");
if ($money != $fee) { echo json_encode(array('r' => -1, 'errmsg' => '升级为VIP会员的支付金额不对')); exit;  }

$openid = $member['login_id'];
if (empty($openid)) { echo json_encode(array('r' => -1, 'errmsg' => 'openid为空')); exit; }

$out_trade_no = 'X' . date('YmdHis') . random(16, 1);
$type = 'xiaochengxu_pay'; // 小程序支付
$r = DB::insert('x_pay_log',
    array(
        'uid' => $uid,
        'type' => $type,
        'out_trade_no' => $out_trade_no,
        'fee' => $money,
        'openid' => $openid,
        'stype' => $stype,
        'createtime' => TIMESTAMP
    ),
    1);

if ($r > 0) {
    include_once 'XiaoChengXu.class.php';
    $xiaochengxu = new XiaoChengXu();
    $pay_info = $xiaochengxu->getOrder(
        array(
            'serviceName' => '升级VIP会员',
            'out_trade_no' => $out_trade_no,
            'money' => $money,
            'openid' => $openid
        )
    );
    if ($pay_info) {
        echo json_encode(array('r' => 0, 'pay_info' => $pay_info));
        exit;
    }
}

echo json_encode(array('r' => -1, 'errmsg' => '支付发起失败, 请重新试!'));

?>